package com.ajavaer.framework.aliyun;

import com.ajavaer.framework.common.message.Message;
import com.ajavaer.framework.common.tools.JsonTools;
import com.ajavaer.framework.common.tools.StringTools;
import com.ajavaer.framework.config.AliyunOssConfig;
import com.ajavaer.framework.message.OssResult;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.InputStream;

/**
 * 阿里云对象存储插件
 */
@Component
@ConditionalOnProperty("ajavaer.aliyun.oss.access-key-id")
public class AliyunOss implements InitializingBean {

    private Logger log = LoggerFactory.getLogger(AliyunOss.class);
    @Resource
    private Environment environment;
    @Resource
    private AliyunOssConfig ossConfig;

    private OSSClient ossClient = null;
    private Boolean isDebug = true;


    /**
     * 上传文件
     *
     * @param objectName
     * @param inputStream
     * @return
     */
    public Message<OssResult> putObject(String objectName, InputStream inputStream) {
        try {
            PutObjectResult putObjectResult = ossClient.putObject(this.ossConfig.getBucket(), objectName, inputStream);
            String url = "https://" + this.ossConfig.getBucket() + "." + this.ossConfig.getEndpoint() + "/" + objectName;
            OssResult ossResult = new OssResult();
            ossResult.setUrl(url);
            ossResult.seteTag(putObjectResult.getETag());
            if (isDebug) {
                log.debug("Oss上传成功:" + JsonTools.beanToJson(ossResult));
            }
            return Message.successResult(ossResult);
        } catch (Exception e) {
            log.error("系统异常:" + e.getMessage(), e);
            return Message.fail(HttpStatus.INTERNAL_SERVER_ERROR, "上传失败");
        }
    }

    /**
     * 删除单个资源
     *
     * @see <a href='https://help.aliyun.com/document_detail/84842.html?spm=a2c4g.11186623.6.684.56a1412fuWuwdY'>文档</a>
     */
    public void deleteObject(String objectName) {
        ossClient.deleteObject(ossConfig.getBucket(), objectName);
    }

    /**
     * 通过url得到objectName
     * @param url
     * @return
     */
    public String url2ObjectName(String url) {
        //不能为空
        if (StringTools.isBlank(url)) {
            return "";
        }
        //需要包含桶名和endpint
        if (!url.contains("://" + this.ossConfig.getBucket()) || !url.contains("/" + this.ossConfig.getEndpoint() + "/")) {
            return "";
        }
        url = url.replace("https://", "");
        return url.substring(url.indexOf("/"));

    }


    @Override
    public void afterPropertiesSet() {
        ossClient = new OSSClient(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
        this.isDebug = this.environment.getProperty("ajavaer.debug", Boolean.class, true);
        if (isDebug) {
            log.debug("Aliyun Oss init");
        }
    }
}
